<template>
    <div style="width:100%;height:100%;">
        <vue-office-excel :options="options" :src="url" :style="styles" @rendered="rendered" @error="errorHandler" />
    </div>
</template>


<script>
import '@vue-office/excel/lib/index.css'
import * as XLSX from 'xlsx';
import ExcelJS from 'exceljs';
// execl文件预览组件
export default {
    name: "excelPreview",
    components: {
        VueOfficeExcel:() => import("@vue-office/excel"),
    },
    props: {
        fileUrl: {
            type: String,
            default: ''
        },
        fileType: {
            type: String,
            default: ''
        },
        styles: {
            type: Object,
            default: () => {
                return {};
            }
        }
    },
    data() {
        return {
            url: '',
            options: {
                //预览xlsx 设置false 预览xls 设置true
                xls: false,
            }
        }
    },
    mounted() {
        this.render();
    },
    methods:
    {
        render() {
            if (this.fileType == 'xls') {
                //this.options.xls = true;
                //this.url = this.fileUrl;
                this.xhrUtils(this.fileUrl);
            }else{
                this.url = this.fileUrl;
            }
        },
        // 渲染结果
        rendered() {
            console.log('渲染完成')
        },
        errorHandler() {
            console.log('加载失败')
        },
        //下载
        xhrUtils(url) {
            let that = this
            const xhr = new XMLHttpRequest()
            xhr.open('get', url, true)
            xhr.responseType = 'arraybuffer'
            xhr.onload = () => {
                if (xhr.status === 200) {
                    const data = new Uint8Array(xhr.response)
                    that.xlsToXlsx(data)
                } else {
                    console.log(xhr, 'xhr-error')
                    // 弹框提示
                    Message({
                        type: 'error',
                        message: '预览失败，请下载查看'
                    })
                }
            }
            xhr.send();
        },
        //设置背景颜色样式
        async xlsxSetStyles(data,xWorkbook) {
            const workbook = new ExcelJS.Workbook();
            await workbook.xlsx.load(data); // 加载 .xls 数据
            // 遍历工作表
            workbook.eachSheet((sheet, id) => {
                console.log(sheet, id);
                const xSheet = xWorkbook.Sheets[sheet.name]
                sheet.eachRow((row, rowNumber) => {
                    row.eachCell((cell, colNumber) => {
                        console.log("rowNumber",rowNumber,"colNumber",colNumber,row,cell);
                        if(xSheet){
                            const style = xSheet[cell.address].s;
                            if(style){
                                cell.fill = {
                                    type: 'pattern',
                                    pattern: 'solid',
                                    fgColor: { argb: "FF" + style.fgColor.rgb }, // 设置背景色
                                };
                            }
                        }
                    });
                });
            });
            const xlsxBuffer = await workbook.xlsx.writeBuffer();
            const blob = new Blob([xlsxBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            this.url = URL.createObjectURL(blob);
        },
        //.xls文件转.xlsx
        xlsToXlsx(data) {
            // .xls文件转.xlsx
            const workbook = XLSX.read(data, { type: 'buffer' ,cellStyles: true})
            // 将工作簿（workbook）写入XLSX格式的文件
            const xlsxFile = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer', cellStyles: true})
            //const blob = new Blob([xlsxFile], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            //const url = URL.createObjectURL(blob);
            //设置丢失颜色样式
            this.xlsxSetStyles(xlsxFile,workbook);
        },
    },
}
</script>

<style lang="scss" scoped></style>
